/*
 * cookie 封装
 */
import Cookies from 'js-cookie';

import BaseStorage from './base-storage';

let COOKIE_PARAMS = {
    domain: document.domain || '',
    path: '/'
};

class CookieStorage extends BaseStorage {
    // constructor(type, prefix) {
    //     super(type, prefix);
    // }

    /**
     *
     * @param {string} name 字段名子
     * @param {object} payload
     *      params: 设置cookie 需要的参数，如：domain、path等
     *      value: 要存储的值
     */
    setItem(name, payload) {
        payload = payload || {};

        let params = Object.assign(COOKIE_PARAMS, payload.params);
        let value = payload.value || '';
        if (Object.prototype.toString.call(value) === '[object Object]') {
            value = JSON.stringify(value);
        }
        Cookies.set(`${this.prefix}${name}`, value, params);
    }

    /**
     * 要获取的cookie变量名，不传name则反回所有
     * @param {string} name 要获取的cookie变量名，不传name则反回所有
     * @param {*} payload 附加参数，暂时没用用到
     * @returns
     */
    getItem(name, payload) {
        if (name) {
            let data = Cookies.get(`${this.prefix}${name}`);
            try {
                return JSON.parse(data);
            } catch (e) {
                return data;
            }
        }
        return Cookies.get();
    }

    /**
     * 根据名称移除cookie，不传name移除所有cookie
     * @param {*} name 
     * @param {*} payload 移除cookie时的附加信息
     */
    removeItem(name, payload) {
        payload = Object.assign(COOKIE_PARAMS, payload);
        let arr = [];
        // 是否在key前面增加prefix
        let isAddPrefix = false;
        if (name) {
            // 移除指定名字的cookie
            arr = Array.isArray(name) ? name : [name];
            isAddPrefix = true;
        } else {
            isAddPrefix = false;
            // 移除当前域名下所有的cookie
            arr = document.cookie.match(/[^ =;]+(?=)/g);
        }
        try {
            (arr || []).forEach((key) => {
                if(isAddPrefix) {
                    key = `${this.prefix}${key}`
                }
                Cookies.remove(key, payload);
            });
        } catch (err) {
            console.log(err);
        }
    }
}

export default CookieStorage;
